package com.platform.hjt.sys.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.hjt.tools.code.MD5;
import com.hjt.tools.dao.Page;
import com.hjt.tools.dao.PropertyFilter;
import com.hjt.tools.date.DateCreator;
import com.hjt.tools.servlet.ServletUtils;
import com.platform.hjt.base.controller.ReturnBody;
import com.platform.hjt.base.costant.BaseElementCode;
import com.platform.hjt.base.costant.ErrorCode;
import com.platform.hjt.base.costant.StateValue;
import com.platform.hjt.base.costant.UserType;
import com.platform.hjt.base.service.BaseService;
import com.platform.hjt.sys.dao.SysCompanyInfoDAO;
import com.platform.hjt.sys.dao.SysLoginLogDAO;
import com.platform.hjt.sys.dao.SysUserInfoDAO;
import com.platform.hjt.sys.dao.SysUserModelDAO;
import com.platform.hjt.sys.model.SysCompanyInfo;
import com.platform.hjt.sys.model.SysLoginLog;
import com.platform.hjt.sys.model.SysUserInfo;
import com.platform.hjt.sys.model.SysUserModel;
import com.platform.hjt.sys.model.SysUserModelId;

@Service
public class SysUserInfoService extends BaseService{

	@Resource
	private SysUserInfoDAO sysUserInfoDAO;
	@Resource
	private SysLoginLogDAO sysLoginLogDAO;
	@Resource
	private SysCompanyInfoDAO sysCompanyInfoDAO;
	@Resource
	private SysUserModelDAO sysUserModelDAO;
	
	public ReturnBody saveSysUserInfo(SysUserInfo sysUserInfo){
		if(StringUtils.isNotBlank(sysUserInfo.getSysUserInfoId())){
			
			SysUserInfo oldUser = sysUserInfoDAO.get(sysUserInfo.getSysUserInfoId());
			
			if(oldUser == null){
				return new ReturnBody(false, "删除错误，请联系管理员。错误代码:" + ErrorCode.NoEntity.getKey());
			}
			
			//如果不是管理员需要判断权限
			if(!getSessionUserInfo().getUserType().equals(UserType.MASTER.getKey())){
				if(!oldUser.getSysCompanyInfo().getSysCompanyInfoId().equals(getSessionSysCompanyInfo().getSysCompanyInfoId())){
					return new ReturnBody(false, "删除错误，请联系管理员。错误代码:" + ErrorCode.NoPower.getKey());
				}
			}
			
			//删除全部权限
			sysUserModelDAO.batchExecute("delete SysUserModel t where t.sysUserInfo.sysUserInfoId=?", sysUserInfo.getSysUserInfoId());
			
			//禁止修改公司所属
			sysUserInfo.setSysCompanyInfo(null);
			sysUserInfoDAO.updatePerproties(sysUserInfo);

			saveUserModel(sysUserInfo);
			return  new ReturnBody(true, "更新成功");
		}else{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("isDel", false);
			map.put("userAccount", sysUserInfo.getUserAccount());
			SysUserInfo exitUser = sysUserInfoDAO.findUniqueBy(map);
			if(exitUser != null){
				return  new ReturnBody(false, "用户名已存在。");
			}
			
			sysUserInfo.setCreateTime(DateCreator.getCurrentTime());
			sysUserInfo.setIsDel(false);
			sysUserInfo.setUserType(UserType.GUEST.getKey().toString());
			sysUserInfo.setState(StateValue.Enable.getKey());
			
			if(!getSessionUserInfo().getUserType().equals(UserType.MASTER.getKey())){
				sysUserInfo.setSysCompanyInfo(getSessionSysCompanyInfo());
			}
			
			sysUserInfo.setUserPwd(MD5.enPasswd(sysUserInfo.getUserAccount(), BaseElementCode.INIT_PWD));
			sysUserInfoDAO.saveJ(sysUserInfo);
			saveUserModel(sysUserInfo);
			return  new ReturnBody(true, "添加成功");
		}
	}
	
	private void saveUserModel(SysUserInfo userInfo){
		if(StringUtils.isNotBlank(userInfo.getSysModelIds())){
			String[] arr = userInfo.getSysModelIds().split(",");
			for(String id : arr){
				sysUserModelDAO.save(new SysUserModel(new SysUserModelId(id, userInfo.getSysUserInfoId())));
			}
		}
	}
	
	public ReturnBody delSysUserInfo(SysUserInfo sysUserInfo){
		
		SysUserInfo user = sysUserInfoDAO.get(sysUserInfo.getSysUserInfoId());
		
		if(user == null){
			return new ReturnBody(false, "删除错误，请联系管理员。错误代码:" + ErrorCode.NoEntity.getKey());
		}
		
		//如果不是管理员需要判断权限
		if(!getSessionUserInfo().getUserType().equals(UserType.MASTER.getKey())){
			if(!user.getSysCompanyInfo().getSysCompanyInfoId().equals(getSessionSysCompanyInfo().getSysCompanyInfoId())){
				return new ReturnBody(false, "删除错误，请联系管理员。错误代码:" + ErrorCode.NoPower.getKey());
			}
		}
		
		sysUserInfo.setIsDel(true);
		sysUserInfoDAO.updatePerproties(sysUserInfo);
		return  new ReturnBody(true, "删除成功");
	}
	
	public ReturnBody handleChangePwd(){
		SysUserInfo currUser = sysUserInfoDAO.findUniqueBy(PropertyFilter.buildFromHttpRequestAttribute(getRequest()));
		if(currUser == null){
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userName", getRequest().getParameter("username"));
			map.put("isDel", false);
			currUser = sysUserInfoDAO.findUniqueBy(map);
			if(currUser == null){
				return new ReturnBody(false, "账号或者密码错误");
			}
			
			if(!currUser.getUserPwd().equals(MD5.enPasswd(currUser.getUserAccount(), getRequest().getParameter("password")))){
				return new ReturnBody(false, "账号或者密码错误");
			}
		} 
		
		currUser.setUserPwd(MD5.enPasswd(currUser.getUserAccount(), getRequest().getParameter("newPassWord")));
		sysUserInfoDAO.updateJ(currUser);
		return new ReturnBody(true, "修改成功");
	}
	
	public Page<SysUserInfo> getSysUserInfoList(Page<SysUserInfo> page, List<PropertyFilter> propertyFilterList){
		return sysUserInfoDAO.findPage(page, propertyFilterList);
	}
	
	public List<SysUserInfo> getSysUserInfoList(List<PropertyFilter> filters){
		return sysUserInfoDAO.find(filters);
	}
	
	public SysUserInfo getSysUserInfo(List<PropertyFilter> filters){
		return sysUserInfoDAO.findUniqueBy(filters);
	}
	
	public SysUserInfo getSysUserInfo(String propertyName, Object value){
		return sysUserInfoDAO.findUniqueBy(propertyName, value);
	}
	
	public ReturnBody handleCheckUserInfo(String userAccount, String userPwd){
		//账号密码登入
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userAccount", userAccount);
		map.put("userPwd", MD5.enPasswd(userAccount, userPwd));
		map.put("isDel", false);
		map.put("state", StateValue.Enable.getKey());
		SysUserInfo currUser = sysUserInfoDAO.findUniqueBy(map);
		
		if(null == currUser){
			return new ReturnBody(false, "账号或者密码错误");
		}
		
		String currIp = ServletUtils.getIP(getRequest());
		String limitIp = currUser.getUserIpLimit();
		if(StringUtils.isNotBlank(limitIp)){
			try {
				List<String> limitIpList = new ArrayList<String>();
				String[] ips = limitIp.split(",");
				for(String ip : ips){
					if(ip.contains("/")){
						String initIp = StringUtils.substringBeforeLast(ip, ".");
						String ipCount = StringUtils.substring(ip, StringUtils.lastIndexOf(ip, ".")+1);
						String[] ipCountArr = ipCount.split("/");
						int begin = Integer.parseInt(ipCountArr[0]);
						int end = Integer.parseInt(ipCountArr[1]);
						
						for(int i=begin; i<end; i++){
							limitIpList.add(initIp+"."+i);
						}
					} else{
						limitIpList.add(ip);
					}
				}
				if(!limitIpList.contains(currIp)){
					return new ReturnBody(false, "该机器不在登入范围内");
				}
			} catch (Exception e) {
				return new ReturnBody(false, "IP配置出错，请联系管理员");
			}
		}
		
		sysLoginLogDAO.save(new SysLoginLog(currUser, DateCreator.getCurrentTime(), currIp));
		/*if(currUser.getSysDept() != null){
			setSessionDept(sysDeptDAO.findUniqueBy("sysDeptId", currUser.getSysDept().getSysDeptId()));
		}*/
		setSessionUserInfo(currUser);
		
		SysCompanyInfo sysCompanyInfo = sysCompanyInfoDAO.findUnique("select company from SysUserInfo userInfo, SysCompanyInfo company where userInfo.sysCompanyInfo.sysCompanyInfoId = company.sysCompanyInfoId and userInfo.sysUserInfoId = ?",  currUser.getSysUserInfoId());
		setSessionCompany(sysCompanyInfo);
		
		return new ReturnBody(true, "登入成功", "index.html");
	}
	
	@SuppressWarnings("all")
	public List<SysUserInfo> getUserInfoListBySysDeptIds(List<String> deptIds){
		String hql = "select userInfo from SysUserInfo userInfo where userInfo.isDel=false and  userInfo.sysDept.sysDeptId in (:ids) order by userInfo.sortIndex";
		return sysUserInfoDAO.getSession().createQuery(hql).setParameterList("ids", deptIds.toArray(new String[deptIds.size()])).list();
	}
	
}
